package com.deep.nacos.hystrix.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HystrixController {

    private final RestTemplate restTemplate;

    @Autowired
    public HystrixController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 服务调用
     * @param str
     * @return
     */
    @HystrixCommand(fallbackMethod = "getNameFallback")
    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    public String echo(@PathVariable String str) {
        return restTemplate.getForObject("http://tcc-nacos-provider/echo/" + str, String.class);
    }

    /**
     * 超时
     * @param str
     * @return
     */
    @HystrixCommand(fallbackMethod = "getNameFallback2")
    @RequestMapping(value = "/echo2/{str}", method = RequestMethod.GET)
    public String echo2(@PathVariable String str) {
        return restTemplate.getForObject("http://tcc-nacos-provider/echo2/" + str, String.class);
    }

    /**
     * 服务异常
     * @param str
     * @return
     */
    @HystrixCommand(fallbackMethod = "getNameFallback3")
    @RequestMapping(value = "/echo3/{str}", method = RequestMethod.GET)
    public String echo3(@PathVariable String str) {
        return restTemplate.getForObject("http://tcc-nacos-provider/echo3/" + str, String.class);
    }


    /**
     * 出错后会调用该降级方法，返回指定的信息
     * @param username
     * @return
     */
    public String getNameFallback(String username){
        return " this username is not exist ";
    }

    /**
     * 服务超时
     * @param username
     * @return
     */
    public String getNameFallback2(String username){
        return " provider timeout ";
    }

    /**
     * 服务异常
     * @param username
     * @return
     */
    public String getNameFallback3(String username){
        return " provider exception ";
    }
}